import Axios from "axios";
import store from "../store";
import router from "../router";
import {
  Toast,
  Dialog
} from "vant";

function publicObj() {
  this.init();
}

// 请求加载动画
let loadinginstace;

publicObj.prototype = {
  // 初始化
  init: function () {},
  wait: 60,
  timer: null,
  remJs: function () {
    var docEl = document.documentElement,
      resizeEvt =
      "orientationchange" in window ? "orientationch ange" : "resize",
      recalc = function () {
        var clientWidth = docEl.clientWidth;
        if (!clientWidth) return;
        if (clientWidth > 640 && clientWidth <= 768) {
          docEl.style.fontSize = "40px";
        } else if (clientWidth > 768) {
          docEl.style.fontSize = "26px";
        } else {
          docEl.style.fontSize = 20 * (clientWidth / 320) + "px";
        }
      };
    recalc();
    if (!document.addEventListener) return;
    window.addEventListener(resizeEvt, recalc, false);
    document.addEventListener("DOMContentLoaded", recalc, false);
  },
  //加载loading
  getLoading: function (n = "加载中...") {
    loadinginstace = Toast.loading({
      duration: 0, // 持续展示 toast
      forbidClick: true,
      message: n
    });
  },
  //清除加载动画
  closeLoading: function () {
    if (loadinginstace != undefined) {
      loadinginstace.close();
    }
    Toast.clear();
  },
  // 验证码计时
  codeTime: function (el) {
    var _this = this;
    if (_this.wait == 0) {
      el.removeClass("active");
      el.text("重新获取");
      _this.wait = 60;
      clearInterval(_this.timer);
    } else {
      el.addClass("active");
      el.text("" + _this.wait + "s后重发");
      _this.wait--;
      _this.timer = setTimeout(function () {
        _this.codeTime(el, _this.wait);
      }, 1000);
    }
  },
  //null 转成''
  $switch: function (e) {
    if (e == null) {
      return "";
    } else {
      return e;
    }
  },
  // 转分秒
  mssTime: function (mss) {
    if (mss == "") return
    // let m = Math.floor((mss / 60 % 60)) < 10 ? '0' + Math.floor((mss / 60 % 60)) : Math.floor((mss / 60 % 60));
    // let s = Math.floor((mss % 60)) < 10 ? '0' + Math.floor((mss % 60)) : Math.floor((mss % 60));
    let m = Math.floor((mss / 60 % 60));
    let s = Math.floor((mss % 60));
    if (m == 0) {
      return `${s}秒`;
    } else {
      return `${m}分${s}秒`;
    }

  },
  // 图片上传
  uploadFile: function (file, resultFn, getUrl) {
    //上传头像
    if (getUrl == undefined) {
      getUrl = "/user/avatar";
    }

    let fileFormData = new FormData();
    fileFormData.append('file', file);
    Axios.post("/zk" + getUrl, fileFormData)
      .then(function (res) {
        Toast('上传成功')
        resultFn(res.data.url,res.data.fileName);
      })
      .catch(function (err) {
        console.log(err);
        loadinginstace.close();
        Toast('上传失败')
      });
  },
  
  // 正则把手机转成中间四位变成*
  telStar: function (tel) {
    tel = "" + tel;
    var reg = /(\d{3})\d{4}(\d{4})/;
    var tel1 = tel.replace(reg, "$1****$2");
    return tel1;
  },
  // 存cookie
  setCookie: function (name, value, days) {
    var _this = this;
    var domain, domainParts, date, expires, host;
    if (days) {
      date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      expires = "; expires=" + date.toGMTString();
    } else {
      expires = "";
    }
    host = location.host;
    if (host.split('.').length === 1) {
      document.cookie = name + "=" + value + expires + "; path=/";
    } else {
      domainParts = host.split('.');
      domainParts.shift();
      domain = '.' + domainParts.join('.');
      document.cookie = name + "=" + value + expires + "; path=/; domain=" + domain;
      if (_this.getCookie(name) == null || _this.getCookie(name) != value) {
        domain = '.' + host;
        document.cookie = name + "=" + value + expires + "; path=/; domain=" + domain;
      }
    }
  },
  // 读取cookie
  getCookie: function (cookieName) {
    var cookieStr = unescape(document.cookie);
    var arr = cookieStr.split("; ");
    var cookieValue = "";
    for (var i = 0; i < arr.length; i++) {
      var temp = arr[i].split("=");
      if (temp[0] == cookieName) {
        cookieValue = temp[1];
        break;
      }
    }
    return cookieValue;
  },
  // 正则验证输入金额要符合价格
  numberCheck: function (num) {
    var re = /^\d*\.{0,1}\d{0,1}$/;
    return re.exec(num) != null;
  },
  // 输入时验证固定电话
  inputTel: function (tel) {
    var regNum = /^[0-9]*$/; //纯数字
    var regChat = /^0\d{2,3}-?\d{0,8}$/; //中间允许出现横线
    return regNum.test(tel) || regChat.test(tel);
  },
  // 验证手机或固定电话
  checkTel: function (tel) {
    var regMobile = /^1[3456789]\d{9}$/; //手机号
    var regPhone = /^0\d{2,3}-?\d{7,8}$/; //座机号
    return regMobile.test(tel) || regPhone.test(tel);
  },
  // 减计算
  sub: function (num, min) {
    if (num > min) {
      num--;
    }
    return num;
  },
  // 加计算
  add: function (num, max) {
    if (num < max) {
      num++;
    }
    return num;
  },
  // 保留两位小数
  retainTwoFn: function (num) {
    var num_v = Math.ceil(parseInt(num * 10000) / 10 / 10.0);
    return num_v / 100.0;
  },
  // 取到url的参数
  getQueryString: function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
  },
  // 限制数字不能输入e和非数字
  restrictE: function (el) {
    el.keypress(function (e) {
      return /[\d]/.test(String.fromCharCode(e.keyCode));
    });
  },
  // 判断是否过期（年月日格式）
  overdueTime: function (time) {
    var overdueTime = new Date(time + " 23:59:59").getTime();
    var nowTime = new Date().getTime();
    return nowTime > overdueTime;
  },
  // 判断是否过期
  isOverdue: function (time) {
    var overdueTime = new Date(time).getTime();
    var nowTime = new Date().getTime();
    return nowTime > overdueTime;
  },
  // 把时间转化为年月格式
  yearsTime: function (time) {
    var yearsTime = new Date(time);
    let year = yearsTime.getFullYear();
    let month = yearsTime.getMonth() + 1;
    if (month < 10) {
      month = "0" + month;
    }
    return year + "-" + month;
  },
  // 把时间转化为年月日格式
  dateTime: function (time) {
    var yearsTime = new Date(time);
    let year = yearsTime.getFullYear();
    let month = yearsTime.getMonth() + 1;
    let date = yearsTime.getDate(); //得到日期
    if (month < 10) {
      month = "0" + month;
    }
    if (date < 10) {
      date = "0" + date;
    }
    return year + "-" + month + "-" + date;
  },
  // 把时间转化为年月日格式
  minTime: function (times, format) {
    let now = new Date(times);
    let year = now.getFullYear(); //得到年份
    let month = now.getMonth(); //得到月份
    let date = now.getDate(); //得到日期
    let hour = now.getHours(); //得到小时
    let minu = now.getMinutes(); //得到分钟
    let sec = now.getSeconds(); //得到秒
    month = month + 1;
    if (month < 10) month = "0" + month;
    if (date < 10) date = "0" + date;
    if (hour < 10) hour = "0" + hour;
    if (minu < 10) minu = "0" + minu;
    if (sec < 10) sec = "0" + sec;
    let time = "";
    //精确到天
    if (format == 1) {
      time = year + "-" + month + "-" + date;
    }
    //精确到分
    else if (format == 2) {
      time =
        year + "-" + month + "-" + date + " " + hour + ":" + minu + ":" + sec;
    }
    //精确到分
    else if (format == 3) {
      time =
        year + "-" + month + "-" + date + " " + hour + ":" + minu;
    }
    return time;
  },
  // 把时间差转为天数
  DateDiff: function (sDate1, sDate2) {
    //sDate1和sDate2是2006-12-18格式
    let aDate, oDate1, oDate2, iDays;
    aDate = sDate1.split("-");
    oDate1 = new Date(aDate[1] + "-" + aDate[2] + "-" + aDate[0]); //转换为12-18-2006格式
    aDate = sDate2.split("-");
    oDate2 = new Date(aDate[1] + "-" + aDate[2] + "-" + aDate[0]);
    iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24); //把相差的毫秒数转换为天数
    return iDays + 1;
  },
  // JS对象属性名排序
  sortName: function (el) {
    let newData = {};
    Object.keys(el)
      .sort()
      .map(key => {
        newData[key] = el[key];
      });
    return newData;
  },
  // 获取当前时间
  getCurrentDate: function (format) {
    let now = new Date();
    let year = now.getFullYear(); //得到年份
    let month = now.getMonth(); //得到月份
    let date = now.getDate(); //得到日期
    let hour = now.getHours(); //得到小时
    let minu = now.getMinutes(); //得到分钟
    let sec = now.getSeconds(); //得到秒
    month = month + 1;
    if (month < 10) month = "0" + month;
    if (date < 10) date = "0" + date;
    if (hour < 10) hour = "0" + hour;
    if (minu < 10) minu = "0" + minu;
    if (sec < 10) sec = "0" + sec;
    let time = "";
    //精确到天
    if (format == 1) {
      time = year + "-" + month + "-" + date;
    }
    //精确到分
    else if (format == 2) {
      time =
        year + "-" + month + "-" + date + " " + hour + ":" + minu + ":" + sec;
    }
    return time;
  },
  //获取几天前
  timerData(timestemp) {
    const minute = 1000 * 60
    const hour = minute * 60
    const day = hour * 24
    const month = day * 30
    const year = month * 12
    const diffValue = new Date().getTime() - timestemp

    //如果本地时间小于变量时间
    if (diffValue <= 0) {
      return '现在'
    }

    //计算差异时间的量级
    const yearC = diffValue / year
    const monthC = diffValue / month
    const weekC = diffValue / (7 * day)
    const dayC = diffValue / day
    const hourC = diffValue / hour
    const minC = diffValue / minute

    //从大到小排列 满足 1 成立
    const map = {
      [yearC]: '年',
      [monthC]: '月',
      [weekC]: '周',
      [dayC]: '天',
      [hourC]: '小时',
      [minC]: '分钟',
    }

    for (let i in map) {
      if (i >= 1) {
        return `${parseInt(i)}${map[i]}前`
      }
    }
  },
  //登录失效
  getLogin() {
    if (store.state.Models == 'and') {
      window.android.toReLogin();

      //清空登录
      store.state.isLogin = ''
      sessionStorage.clear();
      return false
    }
    Dialog.alert({
      title: '提示',
      message: '未授权，请重新登录',
    }).then(() => {
      //清空登录
      store.state.isLogin = ''
      sessionStorage.clear();
      router.push({
        path: '/login',
        replace: true,
        query: {
          redirect: router.currentRoute.fullPath
        } //登录后再跳回此页面时要做的配置
      });
    });
  },
  //点击返回键
  getReturn: function (obj) {
    // store.state.Models = 'web'
    // return false
    //判断安卓还是ios
    //android终端或者uc浏览器
    if (store.state.Models == 'and') {
      window.android.onBack();
      return false;
    }
    //ios终端
    if (store.state.Models == 'ios') {
      // this.$toast(111)
      let pathUrl = router.history.current.path
      if (pathUrl == '/ross') {
        window.webkit.messageHandlers.iOSAPPFuncation.postMessage({
          'body': 'backAppVC'
        });
        return false
      }


      if (obj.type && obj.type == 'url') {
        router.push(obj.url)
      } else {
        // router.go(-1)
        window.webkit.messageHandlers.iOSDissmissVC.postMessage("ios"); //返回上个页面
      }
      return false;
    }

    if (obj.type && obj.type == 'url') {
      router.push(obj.url)
    } else {
      router.go(-1)
    }
  },
  //通知栏字体颜色
  getSizeColor: function (data) {
    //true是黑色、false是白色
    if (store.state.Models == 'and') {
      if (data === 'w') { //h是黑色，w是白色
        window.android.setStatusBarDarkFont(false);
      } else {
        window.android.setStatusBarDarkFont(true);
      }
    }
    //ios终端 //dark是黑色、light是白色
    if (store.state.Models == 'ios') {
      if (data === 'w') { //h是黑色，w是白色
        window.webkit.messageHandlers.iOSAPPSetStatusFuncation.postMessage({
          'status_color': 'light'
        });
      } else {
        window.webkit.messageHandlers.iOSAPPSetStatusFuncation.postMessage({
          'status_color': 'dark'
        });
      }
    }
  },
  //跳转新页面或重定向   0前进、1重定向
  getNextPage: function (num) {
    console.log(store.state.Models)
    //判断安卓还是ios
    //android终端或者uc浏览器
    if (store.state.Models == 'and') {
      if (num == 0) {
        window.android.addPageCount(1)
      } else {
        window.android.reducePageCount(0)
      }
      return false;
    }
    //ios终端
    if (store.state.Models == 'ios') {
      // this.$toast(111)
      // window.webkit.messageHandlers.iOSAPPFuncation.postMessage({ 'body': 'backAppVC' });
      return false;
    }
  },
  //获取微信验证  extract.js 已封装
  wxShare: function () {
    Axios.get('/api/app/crmconfig/getConfig') //获取微信权限
      .then(res => {
        let appId = res.data.data.appId
        if (this.getQueryString('code')) {

          this.setCookie('wxCode', this.getQueryString('code'))
          this.setCookie('isWxCode', 0)
          let urlPath = window.location.href;
          if (urlPath.indexOf('&code') != -1) {
            urlPath = urlPath.split('&code')[0]
          }
          window.location.href = decodeURIComponent(urlPath)
        } else {
          let url = encodeURIComponent(window.location.href)
          let pages = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
          //我是用的非静默授权，snsapi_userinfo 需要用户手动同意
          window.location.replace(pages)
        }
      })
  },
  //拼接图片地址 有无http 或https
  urlImg: function (url = '') {
    // 判断如果为假 直接结束
    if (!url) return false

    //判断是否含有http 有就不用加http 没有就加http
    let isHttp = url.slice(0, 7)
    if (isHttp == 'https:/' || isHttp == 'http://' || isHttp == ' https:') {
      return url
    } else {
      return "http://wx-001.unionnetwork.com/zk/" + url
    }
  }
};
export default new publicObj();